package ctl

import (
	"fmt"
	"github.com/spf13/cobra"
	"micro-sim/cmd/taskmaster/ctl/command"
	"micro-sim/pkg/taskmaster"
	"os"
)

const (
	cliName           = "taskManager"
	cliDescription    = "A command line client for DAG DEVS task."
	defaultConfigPath = "./task.yaml"
)

var (
	globalFlags = command.GlobalFlags{}
)

var (
	rootCmd = &cobra.Command{
		Use:   cliName,
		Short: cliDescription,
		Run:   runRootCommand,
	}
)

func init() {
	rootCmd.PersistentFlags().StringVarP(&globalFlags.ConfigPath, "config", "c", defaultConfigPath, "Path to the configuration file.")
}

func runRootCommand(cmd *cobra.Command, args []string) {
	if err := taskmaster.Start(globalFlags.ConfigPath); err != nil {
		ExitWithError(ExitError, err)
	}
}

const ExitError = 1

func MustStart() {
	if err := Start(); err != nil {
		ExitWithError(ExitError, err)
	}
}

func Start() error {
	return rootCmd.Execute()
}

func ExitWithError(code int, err error) {
	fmt.Fprintln(os.Stderr, "Error:", err)
	os.Exit(code)
}

func init() {
	cobra.EnablePrefixMatching = true
}
